#include "json-deserializator.h"
#include "deserialization-error.h"

using namespace Core;

JSONDeserializator::JSONDeserializator(const QString& data)
{
    this->data = data.split("\n");
}

void Core::JSONDeserializator::beginObject()
{
    QString line = getNextLine();

    if (line != "{")
        throw EDeserializationError("Cannot start reading object");
}

void JSONDeserializator::endObject()
{
    QString line = getNextLine();

    if (!line.startsWith("}"))
        throw EDeserializationError("Cannot finish reading object");
}

bool Core::JSONDeserializator::atEnd()
{
    return data.isEmpty();
}

QString JSONDeserializator::readPropertyName()
{
    QString line = getNextLine(false);

    QString propertyName = line.left(line.indexOf(":"));

    if (propertyName.isEmpty())
        throw EDeserializationError("Cannot read property name");

    return propertyName;
}

IDeserializator::PropertyType JSONDeserializator::readPropertyType()
{
    QString line = getNextLine(false);

    if (line.endsWith("["))
    {
        getNextLine(false);
        return IDeserializator::List;
    }
    if (line.endsWith(":"))
    {
        getNextLine(false);
        return IDeserializator::Object;
    }

    return IDeserializator::Variant;
}

QVariant JSONDeserializator::readPropertyValue()
{
    QString line = getNextLine();

    QString propertyValue = line.right(line.length() - line.indexOf(":"));

    if (propertyValue.isEmpty() || propertyValue == "[")
        throw EDeserializationError("Cannot read property value");

    return propertyValue;
}

void JSONDeserializator::beginList()
{
}

void JSONDeserializator::endList()
{
    QString line = getNextLine();

    if (!line.startsWith("]"))
        throw EDeserializationError("Cannot finish reading list");
}

IDeserializator::PropertyType JSONDeserializator::readListItemType()
{
    QString line = getNextLine(false);

    if (line.endsWith("["))
    {
        getNextLine(false);
        return IDeserializator::List;
    }
    if (line.endsWith("{"))
    {
        getNextLine(false);
        return IDeserializator::Object;
    }

    return IDeserializator::Variant;
}

QVariant JSONDeserializator::readListItem()
{
    QString line = getNextLine();

    if (line.isEmpty() || line == "[" || line == "{" || line == "]" || line == "}")
        throw EDeserializationError("Cannot read item value");

    return line;
}

QString Core::JSONDeserializator::getNextLine(bool remove)
{
    if (data.isEmpty())
        throw EDeserializationError("No data for deserialization");

    QString line = remove ? data.takeFirst() : data.first();

    return line.simplified();
}
